<template>
  <div class="todo-container">
    <div class="todo-wrap">
      <Header :addTodo="addTodo" />
      <List :todos="todos" :delTodo="delTodo" :updateTodo="updateTodo" />
      <Footer
        :todos="todos"
        :checkAll="checkAll"
        :clearAllCompleteTodos="clearAllCompleteTodos"
      />
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs, watch } from "vue";
import Header from "./components/Header.vue";
import List from "./components/List.vue";
import Footer from "./components/Footer.vue";
import { Todo } from "./types/Todo";
import { saveTodos, readTodos } from "./utils/localStorageUtils";
export default defineComponent({
  name: "App",
  components: { Header, List, Footer },
  // 数据应该用数组存储，数据中的每个数据都是一个对象，对象中应该有三个属性（id,title,isCompleted）
  // 把数组暂且定义在App.vue父级组件
  setup() {
    const state = reactive<{ todos: Todo[] }>({
      todos: [
        // { id: 1, title: "奔驰", isCompleted: false },
        // { id: 2, title: "奥迪", isCompleted: true },
        // { id: 3, title: "宝马", isCompleted: false },
      ],
    });

    // 界面加载完毕后生命周期
    onMounted(()=> {
      setTimeout(()=> {state.todos = readTodos()}, 1000)
    })

    // 添加数据的方法
    const addTodo = (todo: Todo) => {
      state.todos.unshift(todo);
    };

    // 删除数据的方法
    const delTodo = (index: number) => {
      state.todos.splice(index, 1);
    };

    // 修改todo的isCompleted属性的状态
    const updateTodo = (todo: Todo, isCompleted: boolean) => {
      todo.isCompleted = isCompleted;
      console.log(todo);
    };

    // 全选或者全不选
    const checkAll = (isCompleted: boolean) => {
      state.todos.forEach((todo) => {
        todo.isCompleted = isCompleted;
      });
    };

    // 清理所有的选中的数据
    const clearAllCompleteTodos = () => {
      state.todos = state.todos.filter((todo) => !todo.isCompleted);
    };

    // 监视操作：如果todos数据变化了，直接存储到浏览器缓存中
    // watch(
    //   () => state.todos,
    //   (val) => {
    //     // 保存到浏览器缓存
    //     saveTodos(val);
    //   },
    //   { deep: true }
    // );

    watch(() => state.todos, saveTodos, { deep: true });

    return {
      ...toRefs(state),
      addTodo,
      delTodo,
      updateTodo,
      checkAll,
      clearAllCompleteTodos,
    };
  },
});
</script>

<style  scoped>
.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>